/** 将多个文件夹中的所有文件，整合到一个文件夹中。 */
const fs = require('fs');
const path =require('path');

const sourceFile = './source';
const mergeFile = './merge';

//判断存不存在merge文件夹
fs.exists(mergeFile,(exists)=>{
	if(exists){
		//存在即删除文件夹内的所有文件和该文件夹
		deleteAll(mergeFile);
	}
	//创建merge文件夹
	fs.mkdir(mergeFile,err=>{
		if(err){
			throw err;
		}
	})
	console.log('make success')
	//深度遍历文件夹
	deepDirFn(sourceFile);
})

// 删除merge文件夹的文件和文件夹
function deleteAll(deletePath){
	let files = [];
	if(fs.existsSync(deletePath)){
		files = fs.readdirSync(deletePath);
		files.forEach(file=>{
			let curPath = path.join(deletePath,file)
			if(fs.statSync(curPath).isDirectory()){
				deleteAll(curPath);
			}else{
				fs.unlinkSync(curPath);
			}
		});
		fs.rmdirSync(deletePath)
	}
}

// 递归查询文件夹下的文件
function deepDirFn(sourceFile){
	let files = fs.readdirSync(path.resolve(__dirname,sourceFile));
	files.forEach(file=>{
		let curFilePath = path.join(sourceFile,file);
		let fileState = fs.statSync(curFilePath);
		
		//文件
		if(fileState.isFile()){
			//将文件copy到目标目录
			copyFile(path.join(mergeFile,file),curFilePath);
			
		}else if(fileState.isDirectory()){
			deepDirFn(sourceFile + '\/' + file);
		}
	})
}

// 复制文件到指定目录
function copyFile(mergePath,sourcePath){
	let rs = fs.createReadStream(sourcePath);
	rs.on('error',err=>{
		console.log('read error',sourcePath);
	})
	let ws = fs.createWriteStream(mergePath);
	ws.on('error',err=>{
		console.log('write error',mergePath);
	})
	rs.pipe(ws);
}

